package com.unswift.cloud.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;
import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cloud.annotation.logger.QueueReceive;
import com.unswift.cloud.core.CommonOperator;
import com.unswift.cloud.pojo.bo.logger.api.request.LoggerApiRequestQueueBo;
import com.unswift.cloud.pojo.bo.logger.operator.LoggerOperatorQueueBo;
import com.unswift.cloud.pojo.mro.logger.api.request.LoggerApiRequestQueueMro;
import com.unswift.cloud.pojo.mro.logger.operator.LoggerOperatorQueueMro;
import com.unswift.cloud.rabbit.RabbitConstant;
import com.unswift.cloud.service.LoggerApiRequestQueueService;
import com.unswift.cloud.service.LoggerOperatorQueueService;
import com.unswift.utils.ExceptionUtils;

@Component
@Api(value="队列监听", author = "unswift", date = "2023-12-10", version = "1.0.0")
public class QueueListener extends CommonOperator implements RabbitConstant{

	@Autowired
	private LoggerApiRequestQueueService loggerApiRequestQueueService;
	@Autowired
	private LoggerOperatorQueueService loggerOperatorQueueService;
	
	@QueueReceive
	@RabbitListener(queues = LOGGER_API_REQUEST_QUEUE_NAME, containerFactory = "rabbitListenerContainerFactory")
	@ApiMethod(value="api日志Rabbit Mq监听，接收api日志队列消息", params = {@ApiField("api日志对象"), @ApiField("Rabbit Mq消息对象"), @ApiField("Rabbit Mq管道对象")})
	public void loggerApiListener(LoggerApiRequestQueueMro apiRequestMro, Message message, Channel channel) throws Exception {
		final long deliveryTag = message.getMessageProperties().getDeliveryTag();
		try {
			LoggerApiRequestQueueBo apiRequestBo=this.convertPojo(apiRequestMro, LoggerApiRequestQueueBo.class);
			loggerApiRequestQueueService.create(apiRequestBo);
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionUtils.exception("abnormal.queue.consumption", e, e.getMessage());
		}
		channel.basicAck(deliveryTag, false);
	}
	
	@QueueReceive
	@RabbitListener(queues = LOGGER_OPERATOR_QUEUE_NAME, containerFactory = "rabbitListenerContainerFactory")
	@ApiMethod(value="操作日志Rabbit Mq监听，接收操作日志队列消息", params = {@ApiField("操作日志对象"), @ApiField("Rabbit Mq消息对象"), @ApiField("Rabbit Mq管道对象")})
	public void loggerOperatorListener(LoggerOperatorQueueMro operatorMro, Message message, Channel channel) throws Exception {
		final long deliveryTag = message.getMessageProperties().getDeliveryTag();
		try {
			LoggerOperatorQueueBo operatorBo=this.convertPojo(operatorMro, LoggerOperatorQueueBo.class);
			loggerOperatorQueueService.create(operatorBo);
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionUtils.exception("abnormal.queue.consumption", e, e.getMessage());
		}
		channel.basicAck(deliveryTag, false);
	}
}
